// ==========================================
// 备件库管理API - 完整代码
// ==========================================

// ========== 备件管理 ==========

// 添加备件（管理员）
app.post('/api/admin/spare-part/add', async (req, res) => {
    try {
        const { partCode, name, category, brand, model, specifications, unit, unitPrice, minStock, location, remark, adminKey } = req.body;

        const ADMIN_SECRET_KEY = 'repair2024admin';
        if (adminKey !== ADMIN_SECRET_KEY) {
            return res.json({ code: 1003, success: false, message: '密钥错误' });
        }

        if (!partCode || !name) {
            return res.json({ code: 1001, success: false, message: '备件编号和名称为必填项' });
        }

        const [result] = await pool.execute(
            `INSERT INTO spare_parts (part_code, name, category, brand, model, specifications, unit, unit_price, min_stock, location, remark)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            [partCode, name, category, brand, model, specifications, unit || '个', unitPrice, minStock || 0, location, remark]
        );

        res.json({ code: 0, success: true, message: '添加成功', data: { id: result.insertId } });
    } catch (error) {
        console.error('添加备件失败:', error);
        if (error.code === 'ER_DUP_ENTRY') {
            res.json({ code: 2001, success: false, message: '备件编号已存在' });
        } else {
            res.json({ code: 9999, success: false, message: '添加失败' });
        }
    }
});

// 备件列表
app.get('/api/spare-parts', async (req, res) => {
    try {
        const { keyword, category, lowStock, page = 1, pageSize = 20 } = req.query;

        let sql = 'SELECT * FROM spare_parts WHERE 1=1';
        const params = [];

        if (keyword) {
            sql += ' AND (part_code LIKE ? OR name LIKE ?)';
            params.push(`%${keyword}%`, `%${keyword}%`);
        }
        if (category) {
            sql += ' AND category = ?';
            params.push(category);
        }
        if (lowStock === 'true') {
            sql += ' AND current_stock < min_stock';
        }

        sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
        params.push(parseInt(pageSize), (parseInt(page) - 1) * parseInt(pageSize));

        const [rows] = await pool.execute(sql, params);

        res.json({ code: 0, success: true, data: { list: rows } });
    } catch (error) {
        console.error('查询备件失败:', error);
        res.json({ code: 9999, success: false, message: '查询失败' });
    }
});

// 备件详情
app.get('/api/spare-part/:id', async (req, res) => {
    try {
        const { id } = req.params;

        const [rows] = await pool.execute('SELECT * FROM spare_parts WHERE id = ?', [id]);

        if (rows.length === 0) {
            return res.json({ code: 2001, success: false, message: '备件不存在' });
        }

        res.json({ code: 0, success: true, data: rows[0] });
    } catch (error) {
        console.error('查询备件详情失败:', error);
        res.json({ code: 9999, success: false, message: '查询失败' });
    }
});

// 更新备件（管理员）
app.put('/api/admin/spare-part/update', async (req, res) => {
    try {
        const { id, partCode, name, category, brand, model, specifications, unit, unitPrice, minStock, location, remark, adminKey } = req.body;

        const ADMIN_SECRET_KEY = 'repair2024admin';
        if (adminKey !== ADMIN_SECRET_KEY) {
            return res.json({ code: 1003, success: false, message: '密钥错误' });
        }

        if (!id) {
            return res.json({ code: 1001, success: false, message: '缺少备件ID' });
        }

        await pool.execute(
            `UPDATE spare_parts 
             SET part_code = ?, name = ?, category = ?, brand = ?, model = ?, 
                 specifications = ?, unit = ?, unit_price = ?, min_stock = ?, location = ?, remark = ?
             WHERE id = ?`,
            [partCode, name, category, brand, model, specifications, unit, unitPrice, minStock, location, remark, id]
        );

        res.json({ code: 0, success: true, message: '更新成功' });
    } catch (error) {
        console.error('更新备件失败:', error);
        res.json({ code: 9999, success: false, message: '更新失败' });
    }
});

// ========== 库存管理 ==========

// 入库（管理员）
app.post('/api/admin/spare-part/stock-in', async (req, res) => {
    const connection = await pool.getConnection();

    try {
        await connection.beginTransaction();

        const { partId, quantity, unitPrice, operatorOpenid, operatorName, remark, adminKey } = req.body;

        const ADMIN_SECRET_KEY = 'repair2024admin';
        if (adminKey !== ADMIN_SECRET_KEY) {
            return res.json({ code: 1003, success: false, message: '密钥错误' });
        }

        if (!partId || !quantity) {
            return res.json({ code: 1001, success: false, message: '缺少必要参数' });
        }

        const totalPrice = unitPrice ? (unitPrice * quantity) : null;

        // 插入入库记录
        await connection.execute(
            `INSERT INTO spare_part_stock (part_id, type, quantity, unit_price, total_price, operator_openid, operator_name, remark)
             VALUES (?, 'in', ?, ?, ?, ?, ?, ?)`,
            [partId, quantity, unitPrice, totalPrice, operatorOpenid, operatorName, remark]
        );

        // 更新库存
        await connection.execute(
            'UPDATE spare_parts SET current_stock = current_stock + ? WHERE id = ?',
            [quantity, partId]
        );

        await connection.commit();

        res.json({ code: 0, success: true, message: '入库成功' });
    } catch (error) {
        await connection.rollback();
        console.error('入库失败:', error);
        res.json({ code: 9999, success: false, message: '入库失败' });
    } finally {
        connection.release();
    }
});

// 出库（管理员）
app.post('/api/admin/spare-part/stock-out', async (req, res) => {
    const connection = await pool.getConnection();

    try {
        await connection.beginTransaction();

        const { partId, quantity, repairOrderId, operatorOpenid, operatorName, remark, adminKey } = req.body;

        const ADMIN_SECRET_KEY = 'repair2024admin';
        if (adminKey !== ADMIN_SECRET_KEY) {
            return res.json({ code: 1003, success: false, message: '密钥错误' });
        }

        if (!partId || !quantity) {
            return res.json({ code: 1001, success: false, message: '缺少必要参数' });
        }

        // 检查库存
        const [parts] = await connection.execute('SELECT current_stock, unit_price FROM spare_parts WHERE id = ?', [partId]);
        if (parts.length === 0) {
            await connection.rollback();
            return res.json({ code: 2001, success: false, message: '备件不存在' });
        }

        if (parts[0].current_stock < quantity) {
            await connection.rollback();
            return res.json({ code: 2002, success: false, message: '库存不足' });
        }

        const unitPrice = parts[0].unit_price;
        const totalPrice = unitPrice ? (unitPrice * quantity) : null;

        // 插入出库记录
        await connection.execute(
            `INSERT INTO spare_part_stock (part_id, type, quantity, unit_price, total_price, repair_order_id, operator_openid, operator_name, remark)
             VALUES (?, 'out', ?, ?, ?, ?, ?, ?, ?)`,
            [partId, quantity, unitPrice, totalPrice, repairOrderId, operatorOpenid, operatorName, remark]
        );

        // 更新库存
        await connection.execute(
            'UPDATE spare_parts SET current_stock = current_stock - ? WHERE id = ?',
            [quantity, partId]
        );

        await connection.commit();

        res.json({ code: 0, success: true, message: '出库成功' });
    } catch (error) {
        await connection.rollback();
        console.error('出库失败:', error);
        res.json({ code: 9999, success: false, message: '出库失败' });
    } finally {
        connection.release();
    }
});

// 库存记录
app.get('/api/spare-part/stock-records/:partId', async (req, res) => {
    try {
        const { partId } = req.params;

        const [rows] = await pool.execute(
            `SELECT * FROM spare_part_stock WHERE part_id = ? ORDER BY created_at DESC LIMIT 100`,
            [partId]
        );

        res.json({ code: 0, success: true, data: { list: rows } });
    } catch (error) {
        console.error('查询库存记录失败:', error);
        res.json({ code: 9999, success: false, message: '查询失败' });
    }
});

// ========== 维修关联 ==========

// 维修单使用备件
app.post('/api/repair/use-spare-part', async (req, res) => {
    const connection = await pool.getConnection();

    try {
        await connection.beginTransaction();

        const { repairOrderId, partId, quantity, operatorOpenid, operatorName } = req.body;

        if (!repairOrderId || !partId || !quantity) {
            return res.json({ code: 1001, success: false, message: '缺少必要参数' });
        }

        // 检查库存
        const [parts] = await connection.execute('SELECT current_stock, unit_price FROM spare_parts WHERE id = ?', [partId]);
        if (parts.length === 0) {
            await connection.rollback();
            return res.json({ code: 2001, success: false, message: '备件不存在' });
        }

        if (parts[0].current_stock < quantity) {
            await connection.rollback();
            return res.json({ code: 2002, success: false, message: '库存不足' });
        }

        const unitPrice = parts[0].unit_price;
        const totalPrice = unitPrice ? (unitPrice * quantity) : null;

        // 插入使用记录
        const [result] = await connection.execute(
            `INSERT INTO repair_spare_parts (repair_order_id, part_id, quantity, unit_price, total_price)
             VALUES (?, ?, ?, ?, ?)`,
            [repairOrderId, partId, quantity, unitPrice, totalPrice]
        );

        // 插入出库记录
        await connection.execute(
            `INSERT INTO spare_part_stock (part_id, type, quantity, unit_price, total_price, repair_order_id, operator_openid, operator_name, remark)
             VALUES (?, 'out', ?, ?, ?, ?, ?, ?, '维修单使用')`,
            [partId, quantity, unitPrice, totalPrice, repairOrderId, operatorOpenid, operatorName]
        );

        // 更新库存
        await connection.execute(
            'UPDATE spare_parts SET current_stock = current_stock - ? WHERE id = ?',
            [quantity, partId]
        );

        await connection.commit();

        res.json({ code: 0, success: true, message: '使用备件成功', data: { id: result.insertId } });
    } catch (error) {
        await connection.rollback();
        console.error('使用备件失败:', error);
        res.json({ code: 9999, success: false, message: '使用失败' });
    } finally {
        connection.release();
    }
});

// 移除维修单备件
app.post('/api/repair/remove-spare-part', async (req, res) => {
    const connection = await pool.getConnection();

    try {
        await connection.beginTransaction();

        const { repairOrderId, partId, adminKey } = req.body;

        const ADMIN_SECRET_KEY = 'repair2024admin';
        if (adminKey !== ADMIN_SECRET_KEY) {
            return res.json({ code: 1003, success: false, message: '密钥错误' });
        }

        // 查询记录是否存在
        const [rows] = await connection.execute(
            'SELECT * FROM repair_spare_parts WHERE id = ? AND repair_order_id = ?',
            [partId, repairOrderId]
        );

        if (rows.length === 0) {
            await connection.rollback();
            return res.json({ code: 2001, success: false, message: '记录不存在' });
        }

        const record = rows[0];

        // 恢复库存
        await connection.execute(
            'UPDATE spare_parts SET current_stock = current_stock + ? WHERE id = ?',
            [record.quantity, record.part_id]
        );

        // 插入入库记录（恢复）
        await connection.execute(
            `INSERT INTO spare_part_stock (part_id, type, quantity, unit_price, total_price, repair_order_id, remark)
             VALUES (?, 'in', ?, ?, ?, ?, '移除备件恢复库存')`,
            [record.part_id, record.quantity, record.unit_price, record.total_price, repairOrderId]
        );

        // 删除使用记录
        await connection.execute('DELETE FROM repair_spare_parts WHERE id = ?', [partId]);

        await connection.commit();

        res.json({ code: 0, success: true, message: '移除成功' });
    } catch (error) {
        await connection.rollback();
        console.error('移除备件失败:', error);
        res.json({ code: 9999, success: false, message: '移除失败' });
    } finally {
        connection.release();
    }
});

// 维修单备件列表
app.get('/api/repair/spare-parts/:orderId', async (req, res) => {
    try {
        const { orderId } = req.params;

        const [rows] = await pool.execute(
            `SELECT rsp.*, sp.part_code, sp.name, sp.unit
             FROM repair_spare_parts rsp
             LEFT JOIN spare_parts sp ON rsp.part_id = sp.id
             WHERE rsp.repair_order_id = ?
             ORDER BY rsp.created_at DESC`,
            [orderId]
        );

        res.json({ code: 0, success: true, data: { list: rows } });
    } catch (error) {
        console.error('查询维修单备件失败:', error);
        res.json({ code: 9999, success: false, message: '查询失败' });
    }
});

// ========== 统计 ==========

// 备件统计
app.get('/api/admin/spare-parts/stats', async (req, res) => {
    try {
        const { adminKey } = req.query;

        const ADMIN_SECRET_KEY = 'repair2024admin';
        if (adminKey !== ADMIN_SECRET_KEY) {
            return res.json({ code: 1003, success: false, message: '密钥错误' });
        }

        // 总备件数量
        const [total] = await pool.execute('SELECT COUNT(*) as count FROM spare_parts');

        // 低库存数量
        const [lowStock] = await pool.execute('SELECT COUNT(*) as count FROM spare_parts WHERE current_stock < min_stock');

        // 总库存价值
        const [totalValue] = await pool.execute('SELECT SUM(current_stock * unit_price) as value FROM spare_parts');

        res.json({
            code: 0,
            success: true,
            data: {
                totalCount: total[0].count,
                lowStockCount: lowStock[0].count,
                totalValue: totalValue[0].value || 0
            }
        });
    } catch (error) {
        console.error('统计失败:', error);
        res.json({ code: 9999, success: false, message: '统计失败' });
    }
});
